<template>
	<el-container class="group-page">
		<el-aside width="280px" class="group-list-box">
			<div class="group-list-header">
				<div class="search-container">
					<el-input 
						class="search-input"
						v-model="searchText"
						placeholder="搜索群聊"
						clearable
						@input="onSearch">
						<template #prefix>
							<el-icon><Search /></el-icon>
						</template>
					</el-input>
					<el-button 
						@click="showAddGroup()"
						class="add-group-btn"
						type="danger"
						circle
						title="创建群聊">
						<el-icon><Plus /></el-icon>
					</el-button>
				</div>
			</div>

			<el-scrollbar class="group-list">
				<div v-loading="initialLoading" element-loading-text="加载群组中...">
					<div v-for="(group,index) in groupList" :key="index" class="group-item-wrapper">
						<group-item 
							v-show="!group.quit && group.showGroupName.includes(searchText)"
							:group="group"
							:active="group === $store.state.groupStore.activeGroup"
							@click="onActiveItem(group,index)">
						</group-item>
					</div>
					<div v-if="!initialLoading && groupList.length === 0" class="no-data-tip">
						<el-empty description="暂无群聊" :image-size="120">
							<el-button type="danger" @click="showAddGroup()">创建群聊</el-button>
						</el-empty>
					</div>
				</div>
			</el-scrollbar>
		</el-aside>

		<el-container class="group-detail" v-if="activeGroup.id">
			<el-header class="group-header">
				<div class="header-left">
					<span class="group-name">{{ activeGroup.showGroupName }}</span>
					<span class="member-count">({{ groupMembers.length }}人)</span>
				</div>
				<div class="header-right">
					<el-button 
						type="danger" 
						@click="onChatAction(activeGroup)">
						<el-icon><Position /></el-icon>
						发送消息
					</el-button>
				</div>
			</el-header>

			<el-main class="group-content">
				<el-tabs type="border-card">
					<el-tab-pane label="群聊信息">
						<div class="info-section" v-loading="membersLoading" element-loading-text="加载中...">
							<div class="avatar-section">
								<file-upload 
									v-if="isOwner"
									class="avatar-uploader" 
									:action="imageAction"
									:showLoading="true"
									:maxSize="maxSize"
									@success="onUploadSuccess">
									<img 
										v-if="activeGroup.headImage" 
										:src="activeGroup.headImage" 
										class="avatar">
									<div v-else class="avatar-uploader-icon">
										<el-icon><Plus /></el-icon>
									</div>
								</file-upload>
								<head-image 
									v-else 
									class="avatar"
									:size="120"
									:url="activeGroup.headImage"
									:name="activeGroup.showGroupName">
								</head-image>
							</div>

							<el-form 
								class="group-form"
								:model="activeGroup"
								:rules="rules"
								label-width="100px"
								ref="groupForm">
								<el-form-item label="群聊名称" prop="name">
									<el-input 
										v-model="activeGroup.name"
										:disabled="!isOwner"
										maxlength="20">
									</el-input>
								</el-form-item>

								<el-form-item label="群主">
									<el-input :value="ownerName" disabled></el-input>
								</el-form-item>

								<el-form-item label="群公告">
									<el-input
										type="textarea"
										v-model="activeGroup.notice"
										:disabled="!isOwner"
										:rows="4"
										maxlength="1024"
										placeholder="群主未设置">
									</el-input>
								</el-form-item>

								<el-form-item label="群设置">
									<div class="group-settings">
										<el-switch
											v-model="AutoAdd"
											active-text="允许群成员邀请"
											@change="settingAdd">
										</el-switch>

										<el-switch
											v-if="isOwner || groupAdmin === 'Y'"
											v-model="groupProhibition"
											active-text="全体禁言"
											@change="toggleGroupProhibition">
										</el-switch>
										<el-switch
											v-if="isOwner || groupAdmin === 'Y'"
											v-model="groupMemberAdd"
											active-text="设置群聊成员可临时添加"
											@change="toggleGroupMemberAdd">
										</el-switch>
									</div>
								</el-form-item>

								<div class="form-actions">
									<el-button type="danger" @click="onSaveGroup()">保存修改</el-button>
									<el-button 
										v-if="isOwner"
										type="danger"
										@click="onDissolve()">
										解散群聊
									</el-button>
									<el-button
										v-else
										type="danger"
										@click="onQuit()">
										退出群聊
									</el-button>
								</div>
							</el-form>
						</div>
					</el-tab-pane>

					<el-tab-pane label="群成员管理">
						<div class="members-section">
							<div class="members-header">
								<div class="title">群成员列表</div>
								<div class="actions">
									<el-button
										v-if="isOwner"
										type="primary"
										size="small"
										@click="showAdminDialogHandler">
										设置管理员
									</el-button>
									<el-button
										type="primary"
										size="small"
										@click="onInviteMember()">
										邀请成员
									</el-button>
								</div>
							</div>

							<div class="members-container">
								<div v-loading="membersLoading && groupMembers.length === 0" element-loading-text="加载成员中...">
									<div class="members-grid">
										<div 
											v-for="member in displayMembers"
											:key="member.userId"
											v-show="!member.quit"
											class="member-item">
											<group-member
												:member="member"
												:group="activeGroup"
												:ownerId="activeGroup.ownerId"
												:isCurrentUserAdmin="isAdmin">
											</group-member>
										</div>
									</div>
									<div v-if="loading" class="loading-more">
										<el-icon><Loading /></el-icon> 加载更多成员...
									</div>
									<div v-if="!loading && !membersLoading && groupMembers.length === 0" class="no-data-tip">
										暂无群成员
									</div>
								</div>
							</div>
						</div>
					</el-tab-pane>
				</el-tabs>
			</el-main>
		</el-container>

		<el-container v-else class="empty-state">
			<div class="empty-content">
				<el-icon><ChatDotRound /></el-icon>
				<p>请选择群聊</p>
			</div>
		</el-container>

		<add-group-member
			v-model:visible="showAddGroupMember"
			:isAdd="false"
			:groupId="activeGroup.id+''"
			:members="groupMembers"
			@reload="loadGroupMembers"
			@refresh-groups="refreshGroupList"
			@close="onCloseAddGroupMember">
		</add-group-member>

		<add-group-member
			v-model:visible="showAddCreateDialog"
			:isAdd="true"
			:groupId="id+''"
			:members="groupMembers"
			@reload="loadGroupMembers"
			@refresh-groups="refreshGroupList"
			@close="closeCreateGroup">
		</add-group-member>

		<el-dialog
			title="设置管理员"
			v-model="showAdminDialog"
			width="650px"
			:modal-append-to-body="false"
			:append-to-body="false"
			@close="closeAdminDialog">
			<div class="admin-transfer">
				<el-transfer
					v-model="adminIds"
					:data="transferData"
					:titles="['普通成员', '管理员']"
					filterable
					filter-placeholder="请输入成员昵称"
					:props="{
						key: 'userId',
						label: 'showNickName'
					}"
					@change="handleAdminChange">
					<template #default="{ option }">
						<div class="transfer-item">
							<head-image 
								:url="option.headImage" 
								:name="option.showNickName" 
								:size="30">
							</head-image>
							<span class="transfer-item-name">{{ option.showNickName }}</span>
						</div>
					</template>
				</el-transfer>
			</div>
		</el-dialog>
	</el-container>
</template>


<script>
	import GroupItem from '../components/group/GroupItem.vue';
	import FileUpload from '../components/common/FileUpload.vue';
	import GroupMember from '../components/group/GroupMember.vue';
	import AddGroupMember from '../components/group/AddGroupMember.vue';
	import HeadImage from '../components/common/HeadImage.vue';
	import groupMemberApi from "@/api/im/groupMemberApi";
	import groupPermission from '@/utils/groupPermission';
	import groupApi from '@/api/im/group';
	export default {
		name: "group",
		components: {
			GroupItem,
			GroupMember,
			FileUpload,
			AddGroupMember,
			HeadImage
		},
		data() {
			return {
				id: '0',
				searchText: "",
				maxSize: 5 * 1024 * 1024,
				activeGroup: {},
				groupMembers: [],
				showAddCreateDialog: false,
				showAddGroupMember: false,
				groupMemberAdd: false,
				rules: {
					name: [{
						required: true,
						message: '请输入群聊名称',
						trigger: 'blur'
					}]
				},
				displayMembers: [],
				pageSize: 20,
				currentPage: 1,
				loading: false,
				showAdminDialog: false,
				adminIds: [],
				transferData: [],
				transferLoading: false,
				transferCurrentPage: 1,
				transferPageSize: 20,
				gmAPI: new groupMemberApi(),
				initialLoading: true,
				membersLoading: true,
				groupProhibition: false,
				userInfo: null,
				scrollHandler: null
			};
		},
		created() {
			this.init();
			this.userInfo = this.$store.state.userStore.userInfo;
		},
		methods: {
			showAddGroup() {
				if (!this.userInfo) {
					this.$message.warning('请先登录');
					return;
				}
				this.id = '0';
				this.showAddCreateDialog = true;
			},
			closeCreateGroup() {
				this.showAddCreateDialog = false;
				this.id = '0';
				this.refreshGroupList();
			},
			onCloseAddGroupMember() {
				this.showAddGroupMember = false;
				this.refreshGroupList();
			},
			switchChange(e, type){
				var yn = e ? 'Y' : 'N';
				var formData={
					groupId:this.activeGroup.id,
					userId:this.userInfo.id
				}, ynText;
				switch (type) {
					case 'xxmdr':
						formData.disturb=yn
						ynText = e ? '已静默消息' : '已取消静默消息';
						break;
					case 'zdlt':
						formData.top=yn
						ynText = e ? '已置顶' : '已取消置顶';
						break;
					case 'bcdtxl':
						formData.keepGroup=yn
						ynText = e ? '保存' : '已移除';
						break;
					default:
						break;
				}
				this.$http({
						url: "/im/group-member/update",
						method: "put",
						data: JSON.stringify(formData)
					}).then((data) => {
						console.log(data);
						if(data){
							this.activeGroup.disturb = e?'Y':'N';
							this.$store.dispatch("loadGroup").then((res) => {
								this.$store.commit('setGroups', res);
								this.$message({
									title:'提示',
									type: 'info',
									message: '已设置'
								});
							})
						}
					})
			},
			switchChange1(flag){
				let formData={
					id:this.activeGroup.id
				};
				if (this.groupAdmin=='N'&&!this.isAdmin) {
					this.$confirm('当前群聊仅群主和管理员可修改群聊名称', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
					}).then(() => {
						this.$message({
							type: 'success',
							message: '我知道了'
						});  		
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消'
						});          
					});
					return;
				}
				this.$http({
						url: "/group/updatejy",
						method: "put",
						data: formData
					}).then((data) => {
						this.activeGroup.prohibition = flag?'Y':'N';
						this.$store.dispatch("loadGroup").then((res) => {
							this.$store.commit('setGroups', res);
							this.$message({
								title:'提示',
								type: 'info',
								message: '已设置'
							});
						})
							
					})
			},
			settingAdd(flag){
				let formData={
					id:this.activeGroup.id
				};
				if (this.groupAdmin=='N'&&!this.isAdmin) {
					this.$confirm('当前群聊仅群主和管理员可修改群聊名称', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
					}).then(() => {
						this.$message({
							type: 'success',
							message: '我知道了'
						});  		
					}).catch(() => {
						this.$message({
							type: 'info',
							message: '已取消'
						});          
					});
					return;
				}
				this.$http({
						url: "/group/updateAdd",
						method: "put",
						data: formData
					}).then((data) => {
						if(data){
							this.activeGroup.tempAutoAdd =flag?'Y':'N';
							data.forEach((msg) => {//循环删除所有临时会话天
								this.$store.commit("removePrivateChat", msg.friendId);
							})
							this.$store.dispatch("loadGroup").then((res) => {
								this.$store.commit('setGroups', res);
								this.$message({
									title:'提示',
									type: 'info',
									message: '设置'
								});
							})
						}
					})
			},
			onActiveItem(group, index) {
				this.membersLoading = true;
				this.$store.commit("activeGroup", index);
				this.activeGroup = group;
				this.loadGroupMembers();
			},
			onInviteMember() {
				this.showAddGroupMember = true;
			},
			onUploadSuccess(data) {
				this.activeGroup.headImage = data.originUrl;
				this.activeGroup.headImage = data.thumbUrl;
			},
			onSaveGroup() {
				this.$refs['groupForm'].validate((valid) => {
					if (valid) {
						let vo = this.activeGroup;
						this.$http({
							url: "/group/modify",
							method: "put",
							data: vo
						}).then((group) => {
							group.id=group.zid;
							this.$store.commit("updateGroup", group);
							this.$message.success("修改成功");
						})
					}
				});
			},
			onDissolve() {
				this.$confirm(`确认要解散'${this.activeGroup.name}'吗?`, '确认解散?', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: `/group/delete/${this.activeGroup.id}`,
						method: 'delete'
					}).then(() => {
						this.$message.success(`群聊'${this.activeGroup.name}'已解散`);
						this.$store.commit("removeGroup", this.activeGroup.id);
						this.$store.commit("removeGroupChat", this.activeGroup.id);
						this.reset();
					});
				})

			},
			onKick(member) {
				this.$confirm(`确定将成员'${member.showNickName}'移出群聊吗？`, '确认移出?', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: `/group/kick/${this.activeGroup.id}`,
						method: 'delete',
						params: {
							userId: member.userId
						}
					}).then(() => {
						this.$message.success(`已将${member.showNickName}移出群聊`);
						member.quit = true;
					});
				})

			},
			onQuit() {
				this.$confirm(`确认退出'${this.activeGroup.showGroupName}',并清空聊天记录吗？`, '确认退出?', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: `/group/quit/${this.activeGroup.id}`,
						method: 'delete'
					}).then(() => {
						this.$message.success(`您已退出'${this.activeGroup.name}'`);
						this.$store.commit("removeGroup", this.activeGroup.id);
						this.$store.commit("removeGroupChat", this.activeGroup.id);
						this.reset();
					});
				})

			},
			onChatAction(group) {
				let chat = {
					type: 'GROUP',
					targetId: group.id,
					showName: group.showGroupName,
					headImage: group.headImage,
				};
				this.$store.commit("openChat", chat);
				this.$store.commit("activeChat", 0);
				this.$router.push("/home/chat");
			},
			loadGroupMembers() {
				this.membersLoading = true;
				this.currentPage = 1;
				this.displayMembers = [];
				
				this.$http({
					url: `/group/members/${this.activeGroup.id}`,
					method: "get"
				}).then((members) => {
					this.groupMembers = members;
					// 初始只加载第一页数据
					this.displayMembers = this.groupMembers.slice(0, this.pageSize);
					this.groupProhibition = this.activeGroup.prohibition === 'Y';
					
					// 设置滚动监听
					this.$nextTick(() => {
						this.setupScrollListener();
					});
				}).catch((error) => {
					console.error('加载群成员失败:', error);
					this.$message.error('加载群成员失败，请重试');
				}).finally(() => {
					this.membersLoading = false;
				});
			},
			reset() {
				this.activeGroup = {};
				this.groupMembers = [];
			},
			setupScrollListener() {
				// 移除旧的监听器
				this.removeScrollListener();
				
				// 获取成员容器
				const container = document.querySelector('.members-container');
				if (!container) {
					console.error('找不到成员容器元素');
					return;
				}
				
				console.log('设置滚动监听成功', container);
				
				// 创建节流函数
				this.scrollHandler = this.throttle(this.handleScroll, 200);
				
				// 添加滚动监听
				container.addEventListener('scroll', this.scrollHandler);
				
				// 初始检查是否需要加载更多
				this.$nextTick(() => {
					// 手动触发一次检查，如果初始内容不足一屏，则自动加载更多
					if (container.scrollHeight <= container.clientHeight && 
						this.displayMembers.length < this.groupMembers.length) {
						this.loadMoreMembers();
					}
				});
			},
			removeScrollListener() {
				if (this.scrollHandler) {
					const container = document.querySelector('.members-container');
					if (container) {
						container.removeEventListener('scroll', this.scrollHandler);
					}
				}
			},
			handleScroll(e) {
				if (!e || !e.target) return;
				
				const target = e.target;
				const scrollHeight = target.scrollHeight;
				const scrollTop = target.scrollTop;
				const clientHeight = target.clientHeight;
				
				// 当距离底部50px时加载更多
				if (scrollHeight - scrollTop - clientHeight < 50 && !this.loading) {
					this.loadMoreMembers();
				}
			},
			loadMoreMembers() {
				if (this.loading) return;
				if (this.displayMembers.length >= this.groupMembers.length) return;
				
				console.log('加载更多成员...');
				this.loading = true;
				
				// 减少延迟时间，提高响应速度
				setTimeout(() => {
					const start = this.currentPage * this.pageSize;
					const end = start + this.pageSize;
					const newMembers = this.groupMembers.slice(start, Math.min(end, this.groupMembers.length));
					
					// 更新显示数据
					this.displayMembers = [...this.displayMembers, ...newMembers];
					this.currentPage++;
					this.loading = false;
					
					// 检查是否需要继续加载
					this.$nextTick(() => {
						const container = document.querySelector('.members-container');
						if (container && 
							container.scrollHeight <= container.clientHeight && 
							this.displayMembers.length < this.groupMembers.length) {
							// 如果内容高度仍然不足以产生滚动条，继续加载
							this.loadMoreMembers();
						}
					});
					
					console.log(`已加载 ${this.displayMembers.length}/${this.groupMembers.length} 名成员`);
				}, 100); // 减少延迟时间
			},
			showAdminDialogHandler() {
				this.showAdminDialog = true;
				this.initTransferData();
				
				// 等待 DOM 更新后绑定滚动事件
				this.$nextTick(() => {
					const panels = document.querySelectorAll('.el-transfer-panel__body .el-checkbox-group');
						panels.forEach(panel => {
							panel.addEventListener('scroll', this.handleTransferScroll);
						});
				});
			},
			closeAdminDialog() {
				const panels = document.querySelectorAll('.el-transfer-panel__body .el-checkbox-group');
				panels.forEach(panel => {
					panel.removeEventListener('scroll', this.handleTransferScroll);
				});
				this.showAdminDialog = false;
			},
			async handleAdminChange(value, direction, movedKeys) {
				const isAdd = direction === 'right';
				const userId = movedKeys[0];
				
				try {
					// 处理滚动加载
					const panels = document.querySelectorAll('.el-transfer-panel__body .el-checkbox-group');
					panels.forEach(panel => {
						panel.addEventListener('scroll', this.handleTransferScroll);
					});

						await this.gmAPI.updateIsAdmin({
							groupId: this.activeGroup.id,
							userId: userId,
							isAdmin: isAdd ? 'Y' : 'N'
						});

						// 更新本地数据
						const member = this.groupMembers.find(m => m.userId === userId);
						if (member) {
							member.isAdmin = isAdd ? 'Y' : 'N';
						}

						this.$message.success(`${isAdd ? '设置' : '取消'}管理员成功`);
				} catch (error) {
					// 操作失败,回滚穿梭框状态
					if (isAdd) {
						this.adminIds = this.adminIds.filter(id => id !== userId);
					} else {
						this.adminIds.push(userId);
					}
					this.$message.error(`${isAdd ? '设置' : '取消'}管理员失败`);
				}
			},
			toggleGroupProhibition(value) {
				if (!this.isOwner && this.groupAdmin !== 'Y') {
					this.$message.warning('只有群主和管理员可以操作');
					return;
				}
				
				const newStatus = value ? 'Y' : 'N';
				this.$http({
					url: '/group/updatejy',
					method: 'put',
					data: {
						id: this.activeGroup.id,
					}
				}).then(() => {
					this.activeGroup.prohibition = newStatus;
					this.$store.commit('updateGroup', this.activeGroup);
					this.$message.success(value ? '已开启全体禁言' : '已关闭全体禁言');
				}).catch(() => {
					this.groupProhibition = !value; // 恢复开关状态
					this.$message.error('操作失败，请重试');
				});
			},
			toggleGroupMemberAdd(value) {
				let formData = {
					id: this.activeGroup.id
				};
				// 检查权限
				if (!this.isOwner && this.groupAdmin !== 'Y') {
					this.$message.warning('只有群主和管理员可以操作');
					this.groupMemberAdd = !value; // 恢复开关状态
					return;
				}
				
				// 调用API更新设置
				this.$http({
					url: "/group/updateAdd",
					method: "put",
					data: formData
				}).then((data) => {
					if(data){
						// 更新本地状态
						this.activeGroup.tempAutoAdd = value ? 'Y' : 'N';
						// 删除相关临时会话
						data.forEach((msg) => {
							this.$store.commit("removePrivateChat", msg.friendId);
						})
						// 刷新群组列表
						this.$store.dispatch("loadGroup").then((res) => {
							this.$store.commit('setGroups', res);
							this.$message.success(value ? '已允许群成员邀请' : '已禁止群成员邀请');
						})
					}
				}).catch(error => {
					console.error('修改群设置失败:', error);
					this.groupMemberAdd = !value; // 恢复开关状态
					this.$message.error('操作失败，请重试');
				});
			},
			init() {
				this.initialLoading = true;
				this.$http({
					url: "/group/list",
					method: "get"
				}).then((groups) => {
					const uniqueGroups = this.removeDuplicateGroups(groups);
					this.$store.commit("setGroups", uniqueGroups);
				}).finally(() => {
					this.initialLoading = false;
				});
			},
			refreshGroupList() {
				this.initialLoading = true;
				this.$http({
					url: "/group/list",
					method: "get"
				}).then((groups) => {
					const uniqueGroups = this.removeDuplicateGroups(groups);
					this.$store.commit("setGroups", uniqueGroups);
				}).catch((error) => {
					console.error('加载群聊列表失败:', error);
					this.$message.error('刷新群聊列表失败');
				}).finally(() => {
					this.initialLoading = false;
				});
			},
			removeDuplicateGroups(groups) {
				const uniqueMap = new Map();
				groups.forEach(group => {
					if (group.id) {
						uniqueMap.set(group.id.toString(), group);
					}
				});
				return Array.from(uniqueMap.values());
			},
			handleTransferScroll(e) {
				const target = e.target;
				const scrollHeight = target.scrollHeight;
				const scrollTop = target.scrollTop;
				const clientHeight = target.clientHeight;
				
				// 当滚动到距离底部20px时加载更多
				if (scrollHeight - scrollTop - clientHeight < 20) {
					// 根据事件源判断是加载成员列表还是穿梭框数据
					const isTransferPanel = target.closest('.el-transfer-panel__body');
					if (isTransferPanel) {
						this.loadTransferData();
					} else {
						this.loadMoreMembers();
					}
				}
			},
			initTransferData() {
				this.transferData = [];
				this.adminIds = [];
				this.transferCurrentPage = 1;
				this.loadTransferData();
			},
			async loadTransferData() {
				if (this.transferLoading) return;
				
				const start = (this.transferCurrentPage - 1) * this.transferPageSize;
				const end = start + this.transferPageSize;
				
				// 如果已经加载完所有数据，则返回
				if (start >= this.groupMembers.length) return;
				
				this.transferLoading = true;
				
				try {
					const newMembers = this.groupMembers.slice(start, end);
					
					// 更新穿梭框数据
					newMembers.forEach(member => {
						if (member.userId !== this.activeGroup.ownerId) {
							this.transferData.push({
								userId: member.userId,
								showNickName: member.showNickName,
								isAdmin: member.isAdmin,
								headImage: member.headImage
							});
							
							if (member.isAdmin === 'Y') {
								this.adminIds.push(member.userId);
							}
						}
					});
					
					this.transferCurrentPage++;
				} catch (error) {
					console.error('加载穿梭框数据失败:', error);
				} finally {
					this.transferLoading = false;
				}
			},
			// 节流函数
			throttle(fn, delay) {
				let timer = null;
				let lastRun = 0;
				
				return function(...args) {
					const now = Date.now();
					const context = this;
					
					if (now - lastRun < delay) {
						clearTimeout(timer);
						timer = setTimeout(() => {
							lastRun = now;
							fn.apply(context, args);
						}, delay);
					} else {
						lastRun = now;
						fn.apply(context, args);
					}
				};
			}
		},
		computed: {
			groupList() {
				return this.$store.state.groupStore.groups;
			},
			groupAdmin() {
				const currentUser = this.groupMembers.find(
					m => m.userId === this.$store.state.userStore.userInfo.id
				);
				return currentUser ? currentUser.isAdmin : 'N';
			},
			isAdmin() {
				let users = this.userInfo;
				return users.id === this.activeGroup.ownerId ? true : false;
			},
			userInfo() {
				return this.$store.state.userStore.userInfo;
			},
			groupStore() {
				return this.$store.state.groupStore;
			},
			ownerName() {
				let member = this.groupMembers.find((m) => m.userId == this.activeGroup.ownerId);
				return member && member.showNickName;
			},
			isOwner() {
				return this.activeGroup.ownerId === this.$store.state.userStore.userInfo.id;
			},
			imageAction() {
				return `/image/upload`;
			},
			Baneddisturb:{
				get(){
					return this.activeGroup.disturb == 'Y'? true : false;
				},
				set(){}
			},
			getProhibition: {
				get() {
					return this.activeGroup.prohibition == 'Y'? true : false;
				},
				set(){}
			},
			AutoAdd:{
				get(){
					return this.activeGroup.tempAutoAdd == 'Y' ? true :false;
				},
				set(){}
			},
			isCurrentUserAdmin() {
				const currentUserId = this.$store.state.userStore.userInfo.id;
				const currentMember = this.groupMembers.find(m => m.userId === currentUserId);
				return currentMember && currentMember.isAdmin === 'Y';
			},
			isGroupAdmin() {
				return groupPermission.hasManagePermission(this.$store);
			}
		},
		watch: {
			groupMembers: {
				handler() {
					if (this.groupMembers && this.groupMembers.length > 0) {
						this.currentPage = 1;
						this.displayMembers = this.groupMembers.slice(0, this.pageSize);
						this.$nextTick(() => {
							this.setupScrollListener();
						});
					}
				},
				immediate: true
			},
			showAdminDialog(val) {
				if (val) {
					this.initTransferData();
					this.$nextTick(() => {
						const panels = document.querySelectorAll('.el-transfer-panel__body');
						if (panels) {
							panels.forEach(panel => {
								panel.addEventListener('scroll', this.handleTransferScroll);
							});
						}
					});
				} else {
					const panels = document.querySelectorAll('.el-transfer-panel__body');
					if (panels) {
						panels.forEach(panel => {
							panel.removeEventListener('scroll', this.handleTransferScroll);
						});
					}
				}
			}
		},
		created() {
			this.init();
			this.userInfo = this.$store.state.userStore.userInfo;
		},
		beforeUnmount() {
			this.removeScrollListener();
		}
	}
</script>

<style lang="scss" scoped>
.group-page {
	height: 100%;
	display: flex;
	overflow: hidden;

	.group-list-box {
		background-color: #f9fafc;
		border-right: 1px solid #ebeef5;
		display: flex;
		flex-direction: column;
		height: 100%;
		position: relative;
		transition: all 0.3s;

		.group-list-header {
			padding: 16px;
			border-bottom: 1px solid #ebeef5;
			background-color: #fff;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
			z-index: 10;
			position: relative;

			.search-container {
				display: flex;
				align-items: center;
				gap: 12px;

				.search-input {
					flex: 1;

					:deep(.el-input__wrapper) {
						border-radius: 20px;
						box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
						transition: all 0.3s ease;

						&:hover, &:focus {
							box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
						}

						.el-input__prefix-inner {
							color: #909399;
						}
					}
				}

				.add-group-btn {
					min-width: auto;
					font-size: 14px;
					box-shadow: 0 2px 8px rgba(var(--el-color-primary-rgb), 0.35);
					transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);

					&:hover {
						transform: translateY(-2px);
						box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.5);
					}
				}
			}
		}

		.group-list {
			flex: 1;
			overflow-y: auto;
			padding: 8px;

			.group-item-wrapper {
				margin-bottom: 8px;
				transition: transform 0.2s ease;

				&:hover {
					transform: translateY(-2px);
				}
			}

			.no-data-tip {
				padding: 32px 0;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				color: #909399;
				font-size: 14px;
			}
		}
	}

	.group-detail {
		flex: 1;
		background-color: #fff;
		
		.group-header {
			background-color: #fff;
			border-bottom: 1px solid #e6e6e6;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 20px;
			height: 60px;
			
			.header-left {
				.group-name {
					font-size: 16px;
					font-weight: 500;
					color: #333;
				}
				
				.member-count {
					color: #909399;
					margin-left: 8px;
				}
			}
			
			.header-right {
				.el-button {
					padding: 8px 16px;
					border-radius: 4px;
					transition: all 0.3s ease;
					
					.el-icon {
						margin-right: 4px;
					}
					
					&:hover {
						transform: translateY(-2px);
						box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
					}
					
					&:active {
						transform: translateY(0);
					}
				}
			}
		}

		.group-content {
			padding: 20px;
			
			:deep(.el-tabs--border-card) {
				border: none;
				box-shadow: none;
				
				.el-tabs__header {
					background-color: #f5f7fa;
					border: none;
					margin: 0;
				}
				
				.el-tabs__nav {
					border: none;
				}
				
				.el-tabs__item {
					border: none;
					height: 40px;
					line-height: 40px;
					transition: all 0.3s ease;
					
					&.is-active {
						background-color: #fff;
						color: var(--el-color-primary);
						border-bottom: 2px solid var(--el-color-primary);
					}
				}
				
				.el-tabs__content {
					padding: 20px;
				}
			}
		}
	}

	.empty-state {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		
		.empty-content {
			text-align: center;
			color: #909399;
			
			.el-icon {
				font-size: 60px;
				margin-bottom: 20px;
				color: #c0c4cc;
			}
			
			p {
				font-size: 16px;
				margin: 0;
			}
		}
	}
}

// 群成员管理样式
.members-section {
	.members-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20px;
		padding: 0 10px;
		
		.title {
			font-size: 16px;
			font-weight: 500;
			color: var(--el-text-color-primary);
		}
		
		.actions {
			display: flex;
			gap: 12px;
			
			.el-button {
				padding: 8px 16px;
			}
		}
	}
	
	.members-container {
		padding: 0 4px;
		height: 400px;
		overflow-y: auto;
		overflow-x: hidden;
		position: relative;
		scrollbar-width: thin;
		border: 1px solid #f0f0f0;
		border-radius: 4px;
		background-color: #fafafa;
		
		&::-webkit-scrollbar {
			width: 6px;
		}
		
		&::-webkit-scrollbar-thumb {
			background: #bbb;
			border-radius: 3px;
			
			&:hover {
				background: #999;
			}
		}
		
		&::-webkit-scrollbar-track {
			background: transparent;
		}

		.members-grid {
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
			gap: 8px;
			padding: 8px 0;
			
			.member-item {
				background-color: transparent;
				padding: 3px;
				transition: background-color 0.2s ease;
				display: flex;
				align-items: center;
				gap: 3px;
				border-radius: 4px;
				cursor: pointer;

				&:hover {
					background-color: var(--el-fill-color-lighter);
				}
			}
		}
		
		.loading-more {
			text-align: center;
			color: var(--el-text-color-secondary);
			padding: 12px 0;
			font-size: 14px;
			
			.el-icon {
				animation: rotating 1s linear infinite;
				display: inline-block;
				margin-right: 5px;
			}
		}
		
		.no-data-tip {
			text-align: center;
			padding: 32px 0;
			color: var(--el-text-color-secondary);
			font-size: 14px;
		}
	}
}

@keyframes rotating {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

// 群设置样式
.group-settings {
	display: flex;
	flex-direction: column;
	gap: 15px;
	
	:deep(.el-switch) {
		--el-switch-on-color: var(--el-color-primary);
	}
}

// 表单操作按钮样式
.form-actions {
	display: flex;
	gap: 10px;
	margin-top: 20px;
	
	.el-button {
		padding: 12px 20px;
		border-radius: 4px;
		
		&:hover, &:active {
			transform: none;
			box-shadow: none;
		}
	}
}

// 上传头像
.avatar-uploader {
	.el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: all 0.3s;

		&:hover {
			border-color: var(--theme-color);
		}
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 120px;
		height: 120px;
		line-height: 120px;
		text-align: center;
	}

	.avatar {
		width: 120px;
		height: 120px;
		display: block;
		object-fit: cover;
	}
}

// 穿梭框样式保持不变
.admin-transfer {
	padding: 10px 0;
	
	.el-transfer {
		display: flex;
		justify-content: center;
		align-items: flex-start;
		gap: 30px;
		
		.el-transfer-panel {
			width: 250px;
			
			.el-transfer-panel__header {
				padding: 8px 12px;
				background: #f5f7fa;
				
				.el-checkbox__label {
					font-size: 14px;
					font-weight: 500;
				}
			}
			
			.el-transfer-panel__filter {
				margin: 12px;
				
				.el-input__inner {
					height: 32px;
				}
			}
			
			.el-transfer-panel__body {
				height: 350px;
				position: relative;
				
				.el-checkbox-group {
					height: 100%;
					overflow-y: auto;
					padding-right: 10px;
					
					&::-webkit-scrollbar {
						width: 6px;
						position: absolute;
						right: 0;
					}
					
					&::-webkit-scrollbar-thumb {
						background: #ddd;
						border-radius: 3px;
						
						&:hover {
							background: #ccc;
						}
					}
					
					&::-webkit-scrollbar-track {
						background: transparent;
					}
				}
			}
			
			.el-transfer-panel__item {
				padding: 8px 12px;
				display: flex !important;
				align-items: center;
				
				.el-checkbox {
					order: -1;
					margin-right: 10px;
					flex-shrink: 0;
				}
				
				.transfer-item {
					display: flex;
					align-items: center;
					gap: 8px;
					flex: 1;
					min-width: 0;
					
					.transfer-item-name {
						font-size: 13px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}
				}
			}
		}
		
		.el-transfer__buttons {
			padding: 0;
			margin-top: 100px;
			
			button {
				padding: 8px;
				margin: 5px 0;
			}
		}
	}
}

// 调整弹窗样式
.el-dialog__wrapper {
	.el-dialog {
		border-radius: 8px;
		
		.el-dialog__header {
			padding: 20px;
			background: #f5f7fa;
			margin: 0;
			border-bottom: 1px solid #eee;
			
			.el-dialog__title {
				font-size: 18px;
				font-weight: 600;
				color: #333;
			}
		}
		
		.el-dialog__body {
			padding: 0;
			max-height: 500px;
			overflow-y: auto;
		}
		
		.el-dialog__footer {
			padding: 12px 20px;
			border-top: 1px solid #eee;
			background: #f8f8f8;
		}
	}
}

// 美化滚动条
.el-scrollbar__wrap {
	&::-webkit-scrollbar {
		width: 6px;
		height: 6px;
	}

	&::-webkit-scrollbar-thumb {
		background: #ddd;
		border-radius: 3px;

		&:hover {
			background: #ccc;
		}
	}

	&::-webkit-scrollbar-track {
		background: transparent;
	}
}

.el-tabs__content {
	.el-tab-pane {
		height: 100%;
		overflow: visible !important;
	}
}
</style>